﻿using RockBus.Logging.Interfaces;
using RockBus.Monitoring.DataContracts;
using RockBus.MonitoringService.Interfaces;
using System.Threading;

namespace RockBus.Services.SignalR
{
    public class MonitoringHub : RockBusHubBase
    {
        public MonitoringHub(ILogger logger, IMonitoringService monitoringService)
            : base(logger)
        {
            this.MonitoringService = monitoringService;
        }

        private IMonitoringService MonitoringService { get; set; }

        private static Timer UpdateTimer { get; set; }

        private static readonly object _lockObject = new object();

        public void StartTimer()
        {
            if (UpdateTimer == null)
            {
                lock (_lockObject)
                {
                    if (UpdateTimer == null)
                    {
                        UpdateTimer = new Timer(new TimerCallback(this.UpdateCounters), null, 2000, 2000);
                    }
                }
            }
        }

        public void StopTimer()
        {
            if (UpdateTimer == null)
            {
                lock (_lockObject)
                {
                    if (UpdateTimer == null)
                    {
                        UpdateTimer.Dispose();
                        UpdateTimer = null;
                    }
                }
            }
        }

        private void UpdateCounters(object state)
        {
            var performanceCountersResponse = this.MonitoringService.GetCounters();
            this.Clients.All.updateCounters(performanceCountersResponse);
        }
    }
}
